// package-star/pages/warehouse-edit/index.js
import { ManageTargetInfoUpdateMixins } from '../../../behaviors/page';
import { navBack, setTitle, showLoading, hideLoading, chooseLocation, tipSuccess } from '../../../common/env';
import { obj2Arr } from '../../../common/utils';
import { DELIVERY_TYPE, DELIVERY_TYPE_VALUE } from '../../../constants/manage';
import { getWarehouseDetail, editWarehouse } from '../../../api/brd';

Page({
    mixins: [ManageTargetInfoUpdateMixins],
    data: {
        warehouseInfo: {},
        deliverySelect: {
            show: false,
            options: obj2Arr(DELIVERY_TYPE),
            map: DELIVERY_TYPE,
        },
    },
    onLoad(options) {
        const { warehouseId } = options;
        setTitle(warehouseId ? '编辑仓库' : '新建仓库');
        warehouseId && this._handleGetWarehouseInfo(warehouseId);
    },
    async _handleGetWarehouseInfo(warehouseId) {
        showLoading('加载中...');
        const warehouseInfo = await getWarehouseDetail(warehouseId);
        this.setData({ warehouseInfo });
        hideLoading();
    },
    handleChange(e) {
        const { type } = e.currentTarget.dataset;
        const { warehouseInfo } = this.data;
        warehouseInfo[type] = e.detail;
        this.setData({ warehouseInfo });
    },
    async handleChangeAdress() {
        const { warehouseInfo } = this.data;
        let params = warehouseInfo.lat && warehouseInfo.lng ? { latitude: warehouseInfo.lat - 0, longitude: warehouseInfo.lng - 0 } : null;
        const info = await chooseLocation(params);
        const { address, latitude: lat, longitude: lng } = info;
        this.setData({
            'warehouseInfo.address': address,
            'warehouseInfo.lng': `${lng}`,
            'warehouseInfo.lat': `${lat}`,
        });
    },
    handleChangeDelivery(e) {
        this.setData({
            'warehouseInfo.deliveryModes': e.detail,
        });
    },
    handleShowDeliverySelect() {
        this.setData({
            'deliverySelect.show': true,
        });
    },
    async handleSave() {
        const { warehouseInfo } = this.data;
        warehouseInfo.deliveryModes = Object.values(DELIVERY_TYPE_VALUE);
        if (!warehouseInfo.name) {
            tipToast('请输入名称');
            return;
        } else if (!warehouseInfo.linkman) {
            tipToast('请输入联系人');
            return;
        } else if (!warehouseInfo.tel) {
            tipToast('请输入电话');
            return;
        } else if (!warehouseInfo.address) {
            tipToast('请选择地址');
            return;
        } else if (!warehouseInfo.deliveryModes || !warehouseInfo.deliveryModes.length) {
            tipToast('请选择配送方式');
            return;
        }
        showLoading('保存中...');
        const flag = await editWarehouse(warehouseInfo);
        if (flag) {
            hideLoading();
            tipSuccess('保存成功');
            navBack();
        }
    },
})
